package dbinfo

import (
	"context"
	"log"
	"strings"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"spider.com/day/settings"
)

var PgClient *gorm.DB // 声明全局 PG 客户端变量

func ConnectToPG() {
	dsn := "host=localhost user=postgres password=1234 dbname=board port=5432 sslmode=disable"

	// 连接数据库
	var err error
	PgClient, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect to the database")
	}

	// 检查连接
	sqlDB, err := PgClient.DB()
	if err != nil {
		panic("failed to get DB from GORM")
	}

	// 确保连接可用
	if err := sqlDB.Ping(); err != nil {
		panic("failed to ping the database")
	}

	log.Println("Successfully connected to the database!")
}

func DaySaveToPG(klineChan chan []*settings.DayKlinePg) {

	for {
		stockDay, ok := <-klineChan
		if !ok {
			break
		}
		if len(stockDay) > 0 {
			result := PgClient.Clauses(clause.OnConflict{DoNothing: true}).Create(&stockDay)

			// result := PgClient.Create(&stockDay)

			if result.Error != nil {
				log.Println("pg upsert failed", stockDay[0].Symbol)
				continue
			}

		}

	}
}

// func CompareDateAndData(klines []*settings.DayKlinePg) {
// 	PgClient.Where()

// }

func PutStockFromPG(ctx context.Context, stockChan chan settings.StockPg) {
	var stocks []settings.StockPg
	result := PgClient.Where("exist = ?", 1).Find(&stocks).Order("symbol DESC")

	if result.Error != nil {
		log.Println("No record found or an error occurred:", result.Error)
		return
	}

	for _, stock := range stocks {
		// log.Println(stock)
		if !strings.Contains(stock.Name, "ST") && !strings.Contains(stock.Name, "*") && stock.Price > 1000000000 {
			stockChan <- stock
			// break
		}

	}
}
